package ac.github.os.internal.core.action.entity

import ac.github.os.internal.core.action.Action
import ac.github.os.internal.core.action.IEntityAction
import ac.github.os.internal.core.condition.call
import ac.github.os.internal.core.condition.callVoid
import ac.github.os.internal.core.config.StringConfig
import ac.github.os.internal.core.config.get
import ac.github.os.internal.core.holder.damage.DamageHolder
import ac.github.os.internal.core.trigger.EntityTrigger
import ac.github.os.internal.session.Cache
import ac.github.os.internal.session.Session
import org.bukkit.Bukkit
import org.bukkit.event.entity.EntityDamageByEntityEvent
import org.bukkit.event.entity.EntityDamageEvent
import taboolib.common.platform.Awake
import taboolib.common.platform.function.submit


@Awake
class DamageAction : IEntityAction {

    override fun onExecute(session: Session, cache: Cache, config: StringConfig) {
        val ignoreArmor = config.get("ia", false)!!
        var damage = config.get("val", 1.0)!!
        session.callVoid<EntityTrigger> { trigger ->
            submit(async = true) {
                cache.filterIsEntities().forEach {
                    if (ignoreArmor) {
                        val event =
                            EntityDamageByEntityEvent(trigger.entity, it, EntityDamageEvent.DamageCause.CUSTOM, damage)
                        Bukkit.getPluginManager().callEvent(event)
                        damage = event.damage
                    }
                    it.damage(damage)
                }
            }
        }
    }

    override val namespace: String
        get() = "entity:damage"
}

abstract class IDamageAction(val name: String) : Action {
    override val namespace: String
        get() = "damage:$name"

    override fun onExecute(session: Session, cache: Cache, config: StringConfig) {
        val holder = session.holder
        if (holder is DamageHolder) {
            this.run(session, config, holder)
        }
    }

    abstract fun run(session: Session, config: StringConfig, holder: DamageHolder)

    override val type: Action.Type
        get() = Action.Type.AIR
}

@Awake
class SetDamageAction : IDamageAction("set") {

    override fun run(session: Session, config: StringConfig, holder: DamageHolder) {
        config.get<Double>("val", single = true)?.let {
            holder.setDamage(it)
        }
    }

}